<!--  -->
<template>
  <a-modal
    :visible="inerVisible"
    :title="$t('all.autotext129')"
    :footer="null"
    @cancel="handleCancel"
    :width="'80%'"
  >
    <div>
      <FeeDetail
        ref="detail"
        :type="type"
        :costId="inerCostId"
        @init="initDetail"
        :is-modal="true"
        :can-audit="true"
        @refresh="refresh"
      />
    </div>
    <!-- 按钮 -->
    <template>
      <div
        class="modal-btn"
        v-if="paymentDetails.status == $const.EXAMINE_TYPE?.PASSTAX?.value"
      >
        <!-- 返回 -->
        <a-button type="primary" @click="handleCancel">
          {{ $t('all.autotext76') }}
        </a-button>
        <!-- 个税办理 -->
        <a-button type="danger" v-if="isFinance" @click="openPopup(1)">{{
          $t('all.autotext369')
        }}</a-button>
      </div>
      <div
        class="modal-btn"
        v-else-if="paymentDetails.status == $const.EXAMINE_TYPE.DAIZHIFU.value"
      >
        <!-- 手动打款 -->
        <!-- <a-button
          type="primary"
          :loading="payLoading"
          v-if="isFinance && paymentDetails.status == $const.EXAMINE_TYPE.DAIZHIFU.value"
          @click="$refs.moveRef.open()"
        >
          {{ $t('all.autotext1354') }}
        </a-button> -->
        <!-- 支付 -->
        <a-button
          type="primary"
          :loading="payLoading"
          v-if="isFinance"
          @click="$refs.identityRef.open()"
        >
          {{ $t('all.autotext736') }}
        </a-button>
        <a-button type="primary" ghost @click="handleCancel">
          {{ $t('all.autotext76') }}
        </a-button>
      </div>
      <div
        class="modal-btn"
        v-else-if="
          showActionBtn &&
          $auth('FEE_REVIEW.FEE_REVIEW_EDIT') &&
          paymentDetails.status !== -11 &&
          paymentDetails.status !== -12
        "
      >
        <!-- 同意 -->
        <a-button type="primary" @click="openPopup(true)">{{
          middleApprove ? $t('all.autotext1822') : $t('all.autotext694')
        }}</a-button>
        <!-- 驳回 -->
        <a-button type="danger" @click="openPopup(false)">{{
          middleApprove ? $t('all.autotext1823') : $t('all.autotext515')
        }}</a-button>
      </div>
    </template>
    <movement ref="moveRef" :costId="inerCostId" @ok="moveOk"></movement>
    <identityCheck ref="identityRef" @ok="checkOk" />
  </a-modal>
</template>

<script>
import { getAuditCheck } from '../../api/cost/audit'
import FeeDetail from '../cost-apply/FeeDetail'
import identityCheck from './components/identityCheck'
import movement from './components/movement'

export default {
  name: 'payDetail',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    costId: {
      type: Number,
      default: 0
    },
    type: {
      type: Number,
      default: 0
    },
    advancedPay: {
      type: Number,
      default: 0
    }
  },
  components: { identityCheck, FeeDetail, movement },
  watch: {
    visible(val) {
      this.inerVisible = val
      this.inerCostId = this.costId
      if (val) {
        this.$nextTick(() => {
          console.log('val', val)
          console.log('costId', this.costId)
          // eslint-disable-next-line no-unused-expressions
          this.$refs?.detail?.getInfo()
          this.auditCheck()
        })
      }
    },
    processList(val) {
      const res = val.find((v) => v.resultOrAction === 2 && v.roleCode) || {}
      const isRole = this.$store.getters.role.code === res.roleCode
      if (!isRole) {
        this.showActionBtn = false
      } else {
        // 到角色
        this.showActionBtn = isRole
      }
      // 到人
      if (res.processType === 1) {
        this.showActionBtn = res.processorId
          ? res.processorId
              .split(',')
              .includes(String(this.$store.state.user.info.id))
          : false
      }
    }
  },
  data() {
    return {
      inerVisible: false,
      inerCostId: '',
      showActionBtn: false,
      paymentDetails: {},
      identityCheckShow: false,
      processList: [], // 申请记录
      flowNodeList: [], // 审批节点
      isSiteCrc: true, // 是否当前site的CRC，不是CRC的时候不需要这个判段，所以默认是true好一点
      isFinance: 0, // 个税凭证和支付只有项目管理员可以看到 （之前这个功能是财务负责，现在变成了项目管理员）
      payLoading: false,
      proFlowNodeCode: '',
      hasBalance: false,
      auditCheckStatus: 0
    }
  },
  computed: {
    middleApprove() {
      // offline: 1 系统自动支付 2 非系统
      if (
        !this.proFlowNodeCode ||
        this.flowNodeList.length < 2 ||
        this.paymentDetails.offline !== 2
      )
        return false
      const reFlowNodeList = this.flowNodeList.filter(
        (v) => v.roleCode !== 'SYS_FINANCE'
      )
      const finPro = reFlowNodeList.findIndex(
        (v) => v.code === this.proFlowNodeCode
      )
      return finPro + 1 < reFlowNodeList.length - 1
    }
  },
  // computed: {
  //   showActionBtn () {
  //     console.log(this.processList)
  //     const res = this.processList.find(v => v.resultOrAction === 2 && v.roleCode) || {}
  //     const isRole = this.$store.getters.role.code === res.roleCode
  //     console.log(isRole)
  //     if (!isRole) return false
  //     // 到人
  //     if (res.processType === 1) {
  //       return res.processorId ? res.processorId.split(',').includes(String(this.$store.state.user.info.id)) : false
  //     }
  //     // 到角色
  //     return isRole
  //   }
  // },
  created() {
    this.checkRole()
  },
  methods: {
    auditCheck() {
      getAuditCheck({ id: this.costId }).then((res) => {
        this.auditCheckStatus = res
      })
    },
    open(id) {
      this.inerCostId = id
      this.inerVisible = true
      this.$nextTick(() => {
        // eslint-disable-next-line no-unused-expressions
        this.$refs?.detail?.getInfo()
      })
    },
    refresh() {
      this.$emit('refresh')
    },
    initDetail(val, val2, isSiteCrc, flowNodeList = [], currentNodeCode = '') {
      this.paymentDetails = val
      this.processList = val2
      this.isSiteCrc = isSiteCrc
      this.flowNodeList = flowNodeList
      this.proFlowNodeCode = currentNodeCode
    },
    // 判断角色
    checkRole() {
      this.isFinance = this.$store.getters.roles[0].code === 'PROJECT_ADMIN'
    },
    openPopup(value) {
      if (value === 1) {
        const item = {
          status: value,
          id: this.paymentDetails.id,
          applyNo: this.paymentDetails.applyNo,
          oldStatus: this.paymentDetails.status,
          personalTax: this.paymentDetails.personalTax,
          totalAmount: this.paymentDetails.totalAmount
        }
        this.$emit('openPopup', item)
      } else {
        const item = {
          status: value,
          id: this.paymentDetails.id,
          applyReason: this.paymentDetails.applyReason,
          applyNo: this.paymentDetails.applyNo,
          userName:
            this.paymentDetails.ptsNo || this.paymentDetails.researchAccount,
          totalAmount: this.paymentDetails.totalAmount,
          type: this.paymentDetails.type,
          middleApprove: this.middleApprove
        }
        // 给0表示正常执行 给1表示垫付项目预算不足需要提醒不阻断 2表示非垫付项目预算不足需要阻断 3表示非垫付项目入账不足需要阻断
        if (value === true) {
          if (this.auditCheckStatus === 0) {
            this.$emit('openPopup', item)
          } else if (this.auditCheckStatus === 1) {
            return this.$confirm({
              title: '提示',
              content: '当前垫付项目的项目预算剩余金额不足！',
              onOk: () => {
                this.$emit('openPopup', item)
              }
            })
          } else {
            return this.$error({
              title: '提示',
              content:
                this.auditCheckStatus === 2
                  ? '当前非垫付项目的项目预算剩余金额不足！'
                  : '当前非垫付项目的入账剩余金额不足！'
            })
          }
        } else {
          this.$emit('openPopup', item)
        }

        // if (!this.hasBalance && value === true) {
        //   if (!this.advancedPay) {
        //     return this.$error({
        //       title: '提示',
        //       content: '当前非垫付项目余额不足，无法支付'
        //     })
        //   } else if (this.advancedPay === 1) {
        //     return this.$confirm({
        //       title: '提示',
        //       content: '当前垫付项目的项目预算剩余金额不足',
        //       onOk: () => {
        //         this.$emit('openPopup', item)
        //       }
        //     })
        //   }
        // } else {
        //   this.$emit('openPopup', item)
        // }
      }
    },
    // 关闭回调
    handleCancel() {
      this.inerVisible = false
      this.$emit('closeCallback')
    },
    checkOk() {
      this.$emit('payRecord')
    },
    moveOk() {
      this.$emit('moveSuccess')
    }
  }
}
</script>
<style scoped>
.modal-btn {
  display: flex;
  justify-content: flex-end;
  padding-top: 24px;
}
.modal-btn button {
  margin-left: 12px;
}
</style>
